// pages/expense/expense.ts
import ExpenseApi from "../../api/ExpenseApi"
import Toast from "tdesign-miniprogram/toast/index"
import { formatToDate } from "../../utils/DateUtil"

const today = new Date()

Page({

  /**
   * 页面的初始数据
   */
  data: {
    amount: "",
    note: "请选择",
    remark: "",
    minDate: new Date(today.getMonth() ? today.getFullYear() : today.getFullYear() - 1, today.getMonth() || 11, 1).getTime(),
    maxDate: new Date().getTime(),
    expenseTimeVal: new Date().getTime(),
    expenseTime: "",
    priceError: false,
  },
  onPriceInput(e: any) {
    const { priceError } = this.data
    const isNumber = /^\d+(\.\d+)?$/.test(e.detail.value)
    if (priceError === isNumber) {
      this.setData({
        priceError: !isNumber,
      })
    }
  },
  handleCalendar() {
    this.setData({ visible: true })
  },
  handleDateConfirm(e: any) {
    const { value } = e.detail

    this.setData({
      note: formatToDate(value),
      expenseTime: formatToDate(value),
      expenseTimeVal: value
    })
  },
  handleConfirm() {
    let { amount, expenseTime, remark } = this.data
    if (!amount) {
      Toast({
        context: this,
        selector: '#t-toast',
        message: "请输入金额",
      })
      return
    }
    if (!expenseTime) {
      Toast({
        context: this,
        selector: '#t-toast',
        message: "请选择时间",
      })
      return
    }
    ExpenseApi.save({ amount, expenseTime, remark }).then(_ => {
      Toast({
        context: this,
        selector: '#t-toast',
        message: '提交成功',
        theme: 'success',
        direction: 'column',
      })
      setTimeout(() => {
        wx.navigateBack()
      }, 300)
    }).catch(e => Toast({
      context: this,
      selector: '#t-toast',
      message: e,
    }))
  },
})
